package com.aysafety.iotdataplatformclient.configurer;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

@Configuration
@MapperScan(basePackages = MssqlDriverForHydraulicSupportConfig.PACKAGE,
    sqlSessionFactoryRef = "hydraulicSupportSqlSessionFactory")
public class MssqlDriverForHydraulicSupportConfig {

    static final String PACKAGE = "com.aysafety.iotdataplatformclient.**.hydraulicSupport.dao";

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean
    @Qualifier("dataSourceHydraulicSupport")
    @ConfigurationProperties("spring.datasource.druid.hydraulicsupport")
    public DataSource dataSourceHydraulicSupport() {
        logger.info("-------------------- dataSourceHydraulicSupport init ---------------------");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public JdbcTemplate hydraulicSupportJdbcTemplate(@Qualifier("dataSourceHydraulicSupport") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }


    @Bean
    public SqlSessionFactory hydraulicSupportSqlSessionFactory(
        @Qualifier("dataSourceHydraulicSupport") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources("classpath:com/aysafety/iotdataplatformclient/**/hydraulicSupport/mapper/*.xml"));
        sessionFactory
            .setConfigLocation(new DefaultResourceLoader().getResource("classpath:config/mybatis-config.xml"));
        return sessionFactory.getObject();
    }

    @Bean
    public DataSourceTransactionManager hydraulicSupportTransactionManager(
        @Qualifier("dataSourceHydraulicSupport") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate hydraulicSupportSqlSessionTemplate(
        @Qualifier("hydraulicSupportSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
